﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace WordsReverser
{
    class WordsReverser
    {
        public static string ReverseWords(string sentence)
        {
            string indentedText = " " + sentence;
            Regex regex = new Regex(@"\s\w+|\S+");
            var matches = regex.Matches(indentedText);
            List<string> stringMatches = new List<string>();
            foreach (var item in matches)
            {
                stringMatches.Add(item.ToString());
            }
            int index = stringMatches.Count - 1;
            string newText = regex.Replace(indentedText, new MatchEvaluator(
                (x) =>
                {
                    index--;
                    if (index >= 0)
                    {
                        return stringMatches[index].ToLower();
                    }
                    else
                    {
                        return stringMatches[stringMatches.Count - 1];
                    }
                }));
            newText = newText.Trim();
            newText = newText[0].ToString().ToUpper() + newText.Substring(1);
            return newText;
        }

        static void Main(string[] args)
        {
            string text = "A lass is picking, berries.";
            string reversed = ReverseWords(text);
            Console.WriteLine(reversed);
        }
    }
}
